package com.qk.exception;

import com.qk.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j
@RestControllerAdvice
public class GlobalException {
    //捕获所有的异常
    @ExceptionHandler
    public Result handleException(Exception e){
        log.error("异常信息",e);
        return Result.error("网络错误，换个路由器");
    }
    //捕获DuplicateKeyException异常
    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e){
        String errMsg=e.getMessage();
        if(errMsg.contains("Duplicate entry")){
            String msg=errMsg.substring(errMsg.indexOf("Duplicate entry"));
            String [] arr=msg.split(" ");
            return Result.error(arr[2]+"已存在");
        }
        return Result.error("对不起，路由器过期了");
    }
    //捕获登录的异常
    @ExceptionHandler
    public Result handleBusinessException(BusinessException e){
        log.error("异常信息",e);
        return Result.error(e.getMessage());
    }
}
